package weixin

import (
	"context"

	"github.com/ArtisanCloud/PowerWeChat/v3/src/miniProgram"
)

type Weixin struct {
	appId string
	secrt string
	app   *miniProgram.MiniProgram
}

func NewApp(appId string, secrt string) (*Weixin, error) {
	// 1. 初始化小程序应用实例
	app, err := miniProgram.NewMiniProgram(&miniProgram.UserConfig{
		AppID:     appId, // 小程序、公众号或者企业微信的appid
		Secret:    secrt, // 商户号 appID
		HttpDebug: true,
		Debug:     false,
	})

	if err != nil {
		return nil, err
	}

	wx := &Weixin{
		appId: appId,
		secrt: secrt,
		app:   app,
	}
	return wx, nil
}

func (wx *Weixin) AuthCode(ctx context.Context, code string) string {

	// 2. 调用小程序的授权登陆接口
	rs, err := wx.app.Auth.Session(ctx, code)
	if err != nil {
		panic(err)
	}

	wx.app.PhoneNumber.GetUserPhoneNumber(ctx, code)

	return rs.OpenID
}
